/* eslint-disable no-undef */
'use strict'

import { ipcMain, dialog } from 'electron'
import fs from 'fs'
import path from 'path'

const EleIndexMinJs = fs.readFileSync(path.join(__static, '/index.min.js'), 'utf-8')
const EleIndexMinCss = fs.readFileSync(path.join(__static, '/index.min.css'), 'utf-8')
const VueMinJs = fs.readFileSync(path.join(__static, '/vue.min.js'), 'utf-8')
if (VueMinJs && EleIndexMinCss && EleIndexMinJs) {
  console.log('load success!!')
} else {
  console.error('load fail!!')
}

const PlaceHolder = {
  ElementCss: '___ElementCss___',
  ElementJs: '___ElementJs___',
  VueJs: '___VueJs___'
}

const handleSourceReplace = (source) => {
  console.log('souorce: ', source)
  // ！！！一定要ElementJs在前！！！
  if (source.indexOf(PlaceHolder.ElementJs) > -1) {
    source = source.replace(PlaceHolder.ElementJs, EleIndexMinJs)
  }
  if (source.indexOf(PlaceHolder.ElementCss) > -1) {
    source = source.replace(PlaceHolder.ElementCss, EleIndexMinCss)
  }
  if (source.indexOf(PlaceHolder.VueJs) > -1) {
    source = source.replace(PlaceHolder.VueJs, VueMinJs)
  }
  return source
}

ipcMain.on('write-file', (event, arg) => {
  let { fileName, fileContent, filters } = arg
  if (!fileContent) return
  filters = filters || [{ name: '文本文件', extensions: ['txt'] }]

  dialog.showSaveDialog({
    defaultPath: fileName,
    filters
  }).then(res => {
    const { filePath, canceled } = res
    if (!canceled) {
      fs.writeFileSync(filePath, fileContent)
      event.reply('write-success')
    }
  }).catch((e) => {
    console.log('file save error: ', e)
  })
})

ipcMain.on('write-html', (event, arg) => {
  let { fileName, fileContent } = arg

  fileContent = handleSourceReplace(fileContent)

  dialog.showSaveDialog({
    defaultPath: fileName,
    filters: [
      {
        name: '网页文件',
        extensions: ['html']
      }
    ]
  }).then(res => {
    const { filePath, canceled } = res
    if (!canceled) {
      fs.writeFileSync(filePath, fileContent)
      event.reply('write-success')
    }
  }).catch((e) => {
    console.error(e)
  })
  // const dirPath = path.join(__dirname, './output')
  // const filePath = path.join(__dirname, './output/', fileName)
  // if (!fs.existsSync(dirPath)) {
  //   fs.mkdirSync(dirPath)
  // }
  // console.log(filePath)
  // fs.writeFileSync(filePath, fileContent)
})
